import { fileURLToPath, URL } from "node:url";
import * as fs from "node:fs/promises";
import * as fss from "node:fs";
import * as path from "node:path";
import * as https from "https";

/* 下载字体图标脚本 */

const __dirname = fileURLToPath(new URL(".", import.meta.url));

// 脚本路径源文件
const configFile = path.join(__dirname, "../src/components/framework/icon/config.json");

// 图标js文件输出目录
const publicDir = "static/icon";
const outDir = path.join(__dirname, `../public/${publicDir}`);

// 脚本输出文件名
const outputFileName = `iconfont.js`;
// 输出文件绝对路径
const outFilePath = path.join(outDir, outputFileName);
// 相对项目public目录的路径
const publicFilePath = path.join(publicDir, outputFileName).replace(/\\/g, "/");

/**
 * @param {string} url
 * @returns {Promise<string>}
 */
function downloadFile(url) {
  return new Promise((resolve, reject) => {
    https.get(url, res => {
      res.setEncoding("utf-8");
      let data = "";
      res.on("data", chunk => {
        data += chunk;
      });

      res.on("end", () => resolve(data));
      res.on("error", e => reject(e));
    });
  });
}

function buildConfigFileContent(originalConfig) {
  return JSON.stringify({ ...originalConfig, scriptUrl: publicFilePath }, null, 2);
}

(async () => {
  if (!fss.existsSync(configFile)) {
    console.log(`[download-iconfont] icon config file not exists: ${configFile}`);
    return;
  }
  const jsonBuf = await fs.readFile(configFile);
  const config = JSON.parse(jsonBuf.toString());
  const { scriptUrl } = config;
  if (scriptUrl.startsWith("https://") || scriptUrl.startsWith("//")) {
    let url = scriptUrl;
    if (url.startsWith("//")) {
      url = `https:${url}`;
    }
    console.log(`[download-iconfont] downloading file: ${url}`);
    downloadFile(url)
      .then(async content => {
        await fs.mkdir(outDir, { recursive: true });
        // 写入图标脚本文件
        await fs.writeFile(outFilePath, content, { encoding: "utf-8" });
        // 修改图标配置文件
        await fs.writeFile(configFile, buildConfigFileContent(config));

        console.log(`[download-iconfont] download success: ${scriptUrl} => ${publicFilePath}`);
      })
      .catch(e => {
        console.error(`[download-iconfont] download failed: ${scriptUrl}`);
        console.error(e);
      });
  } else {
    console.log(`[download-iconfont] icon file is downloaded: ${scriptUrl}`);
    if (!fss.existsSync(outFilePath)) {
      console.error(`[download-iconfont] icon file is not exists: ${outFilePath}`);
    }
  }
})();
